#!/usr/bin/perl
# SCRIPT PAGE
use strict;
use warnings;
require 'forum_common.pl';

connect_to_database() or bad_deal();
my $user = get_current_user(get_sess_id());

record_this_hit();

my $topic_id = url_param('topic');
bad_deal('No topic specified!') unless (defined $topic_id);


my $topic;
bad_deal() unless ($topic = get_topic($topic_id) and
					!($forum::errmsg = cant_makepost($user, $topic)));
my $topic_title = escapeHTML($topic->{TITLE});
my $board_title = escapeHTML($topic->{B_TITLE});

my ($msg, $content) = ('');
if (defined($content = param('content')) && $ENV{'REQUEST_METHOD'} eq 'POST')
{
	my ($submit, $post_id, $ip_addr, $hostname);
	$ip_addr = $ENV{'REMOTE_ADDR'};
	$hostname = $ENV{'REMOTE_HOST'};
	if (defined($submit = param('submit')) && $submit eq $forum::preview_text)
	{
		my @err = verify_post($content);
		if (@err)
		{
			$msg = forum_error('', join(br(), @err));
		}
		else
		{
			if (-f 'resources/tobias-quotes.txt')
			{
				open FILE, 'tobias-quotes.txt';
				my @quotes = <FILE>;
				close FILE;
				my $count = scalar(@quotes);
				$msg = div({-class=>'funny'}, @quotes[rand $count]);
			}
			#$msg = forum_error('Dan, I hat you');
		}
		$msg .= div({-id=>'post_preview'}, as_post($content));
	}
	elsif ($post_id = make_post($topic, $user, $content, $ip_addr, $hostname))
	{
		print redirect(-status=>303,
					   -location=>"topic.cgi?id=$topic_id#post$post_id");
		exit;
	}
	else
	{
		$msg = nl2br(forum_error());
	}
}

print header($forum::http_header), forum_start(forum_cpanel($user)),
	"Board: $board_title", br(),
	"Topic: $topic_title", br(),
	br(),
	$msg,
	start_form(-action=>'', -method=>'post'),
	'<fieldset id="makepost">',
	legend('New Post'),
	'Post Content: (max 15000 characters)', br(),
	textarea(-name=>'content', -cols=>100, -rows=>20, -id=>'postcontent'),
	div({-class=>'subbtn'},
		submit(-name=>'submit', -value=>'Preview'),
		submit(-name=>'submit', -value=>'Post')),
	'</fieldset>',
	end_form();


gameover:
print forum_end();
forum_disconnect();
